//
//  ViewController.m
//  newPro
//
//  Created by  Mac on 2017/8/24.
//  Copyright © 2017年  Mac. All rights reserved.
//

#import "ViewController.h"
// 长连接
#import <SRWebSocket.h>
#import <SocketRocket/SocketRocket.h>

@interface ViewController ()<SRWebSocketDelegate>
// 长连接
@property(nonatomic,strong)SRWebSocket * socket;

@property(nonatomic,strong)NSString * messageStr;

@property(nonatomic,strong)NSString * hostStr;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _messageStr = [NSString stringWithFormat:@"{\"content\":{\"order_id\":\"2126\",\"uid\":\"39\"},\"deviceno\":\"A0000055BBD966\",\"method\":\"passengerSyncPrice\",\"type\":\"calculate\",\"uid\":\"39\"}"];
    
    _hostStr = [NSString stringWithFormat:@"ws://yunda.xxxx.net:2167"]; //@"ws://yunda.xxxx.net:2167" 需和服务端对接 2016 端口
    
    
    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:_hostStr]];
    
    _socket = [[SRWebSocket alloc]initWithURLRequest:request];
    
    _socket.delegate = self;
    
    
    [_socket open];
    
}


//这个就是接受消息的代理方法了，这里接受服务器返回的数据，方法里面就应该写处理数据，存储数据的方法了。
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message
{
//    NSDictionary *data = [NetworkUtils decodeData:message];
//    if (!data)
//        return;
    NSLog(@"收到的数据是:%@",message);
    
//    [_socket close];
    
    
}
//这里是Websocket刚刚Open之后的代理方法。就想微信刚刚连接中，会显示连接中，当连接上了，就不显示连接中了，取消显示连接的方法就应该写在这里面
- (void)webSocketDidOpen:(SRWebSocket *)webSocket
{
    [_socket send:_messageStr];
}
//这是关闭Websocket的代理方法
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean
{
//    [self failedConnection:NSLS(Disconnected)];
    NSLog(@"关闭Websocket--------wasClean:%d",wasClean);
    NSLog(@"%@",reason);

    
}
//这里是连接Websocket失败的方法，这里面一般都会写重连的方法
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error
{
//    [self failedConnection:NSLS(Disconnected)];
    NSLog(@"连接失败--------error:%@",error);
    [self _reconnect];
}

- (void)_reconnect;
{
    _socket.delegate = nil;
    [_socket close];
    
    _socket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_hostStr]]];
    _socket.delegate = self;
    
    self.title = @"Opening Connection...";
    
    [_socket open];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
